import React, {Component} from 'react';
import {Button, Row, Col, Form, Input, Table, Modal, DatePicker, Select, Radio, Pagination} from 'antd';
import {EditAdmins} from "../components/EditComponent";
import {ButtonSubmit} from "../components/AddComponent";
import app from '../AppMethod';
import {requestUrl, menu} from "../value";
import moment from 'moment';
import {Consumer} from "../store";

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const confirm = Modal.confirm;

class AdminManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            data: [],
            pagination: {
                current: 0,
                total: 0,
                pageSize: 0
            },
            allPage: 0,
            searchData: {},
            editVisible: false,
            addConfirmLoading: false,
            isAddValid: false,
            roleItem: []
        }
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };
    columns = [
        {
            title: '账号',
            dataIndex: 'admin_username'
        },
        {
            title: '昵称',
            dataIndex: 'admin_nickname'
        },
        {
            title: '角色名',
            dataIndex: 'role_name'
        },
        {
            title: '创建时间',
            dataIndex: 'admin_createtime'
        },
        {
            title: '登录次数',
            dataIndex: 'admin_times'
        },
        {
            title: '最后登录时间',
            dataIndex: 'admin_login'
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                    <EditAdmins roleItem={this.state.roleItem} data={data} handleEdit={() => this.handleEdit()}/>
                        <span style={{color: '#f5222d', cursor: 'pointer', marginLeft: '10px'}}
                              onClick={() => this.handleDelete(data.admin_id)}>删除</span>
                    </span>
                )
            }
        }
    ];

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <SearchLists
                        clickSearch={(value) => {
                            this.handleGetSearch(value)
                        }}
                        handleReset={() => {
                            this.handleReset()
                        }}
                        roleItem={this.state.roleItem}
                    >
                    </SearchLists>
                </Row>
                <Row>
                    <ButtonSubmit
                        isVisible={this.state.isAddValid == null ? false : this.state.isAddValid}
                        title="添加管理员" buttonText={'添加管理员'} width="500px"
                        addConfirmLoading={this.state.addConfirmLoading}
                        click={(e) => this.handleCancel(true)}
                        clickOk={(e) => this.handleSubmit(e)}
                        clickCancel={(e) => this.handleCancel(false)}
                    >
                        <Row>
                            <Col offset={1} span={22}>
                                <Form className="login-form">
                                    <FormItem label="账号" {...this.formItemLayout}>
                                        {
                                            getFieldDecorator('username', {
                                                rules: [{required: true, message: '请输入账号'}]
                                            })(
                                                <Input placeholder="请输入"/>
                                            )
                                        }
                                    </FormItem>
                                    <FormItem label="密码" {...this.formItemLayout}>
                                        {
                                            getFieldDecorator('password', {
                                                rules: [{required: true, message: '请输入密码'}]
                                            })(
                                                <Input placeholder="请输入" type="password"/>
                                            )
                                        }
                                    </FormItem>
                                    <FormItem label="角色" {...this.formItemLayout}>
                                        {
                                            getFieldDecorator('role_id', {
                                                rules: [{required: true, message: '请选择角色'}]
                                            })(
                                                <Select placeholder="请选择角色">
                                                    {
                                                        this.state.roleItem.map((item) => {
                                                            return (
                                                                <Option key={item.role_id}
                                                                        value={item.role_id}>{item.role_name}</Option>
                                                            )
                                                        })
                                                    }
                                                </Select>
                                            )
                                        }
                                    </FormItem>
                                    <FormItem label="昵称" {...this.formItemLayout}>
                                        {
                                            getFieldDecorator('nickname', {
                                                rules: [{required: true, message: '请输入昵称'}]
                                            })(
                                                <Input placeholder="请输入" key="1"/>
                                            )
                                        }
                                    </FormItem>
                                </Form>
                            </Col>
                        </Row>
                    </ButtonSubmit>
                    <Button type="primary" style={{marginLeft: '10px'}} onClick={() => this.handleRefresh()}
                    >
                        刷新
                    </Button>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Col span={24}>
                        <Table
                            columns={this.columns}
                            rowKey={record => record.admin_id}
                            dataSource={this.state.data}
                            pagination={false}
                            loading={this.state.loading}
                        />
                    </Col>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Col span={12} style={{fontSize: '15px'}}>
                        共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current} / {this.state.allPage}
                        页
                    </Col>
                    <Col span={12} style={{textAlign: 'right'}}>
                        <Pagination {...this.state.pagination} showSizeChanger={true} showQuickJumper={true}
                                    onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}
                                    onShowSizeChange={(current, size) => this.handleSizeChange(current, size)}
                                    hideOnSinglePage={false}/>
                    </Col>
                </Row>
            </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "管理员列表"});
        this.handleSearchAdminList();
        this.handleSearchRoleList();
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        };
    };

    /**
     * 处理搜索管理员列表事件
     * @param data
     */
    handleSearchAdminList(data = {page: 1, size: 10}) {
        this.setState({loading: true});
        app.post(requestUrl.SEARCH_ONEADMIN, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                let AdminListData = result.data.dataSet;
                for (let i = 0; i < AdminListData.length; i++) {
                    AdminListData[i].admin_login = AdminListData[i].admin_login === null ? '' : moment(AdminListData[i].admin_login).format('YYYY-MM-DD');
                    AdminListData[i].admin_createtime = AdminListData[i].admin_createtime === null ? '' : moment(AdminListData[i].admin_createtime).format('YYYY-MM-DD');
                }
                this.setState({data: AdminListData, loading: false, pagination, allPage});
            } else {
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                app.alert(result.msg, 'error', 3);
                this.setState({data: [], loading: false, pagination, allPage});
            }
        })
    };

    /**
     * 处理搜索角色列表事件
     */
    handleSearchRoleList() {
        app.post(requestUrl.SEARCH_ROLELIST, {}).then((result) => {
            if (result.code === 1) {
                this.setState({roleItem: result.data.dataSet});
            } else {
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 处理修改事件
     */
    handleEdit() {
        this.handleRefresh();
    }

    /**
     * 处理查询列表事件
     * @param value
     */
    handleGetSearch(value) {
        this.setState({searchData: value});
        let data = {
            page: 1,
            size: this.state.pagination.pageSize || 10,
            ...value
        };
        this.handleSearchAdminList(data);
    };

    /**
     * 处理刷新按钮事件
     */
    handleRefresh() {
        let data = this.state.searchData;
        data.page = this.state.pagination.current ? this.state.pagination.current : 1;
        data.size = this.state.pagination.pageSize ? this.state.pagination.pageSize : 10;
        this.handleSearchAdminList(data);
    };

    /**
     * 处理删除后刷新列表功能
     */
    handleAfterDel() {
        let data = this.state.searchData;
        data.page = 1;
        data.size = 10;
        this.handleSearchAdminList(data);
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        this.handleSearchAdminList(data);
    };

    /**
     * 处理页数变化事件
     * @param current
     * @param size
     */
    handleSizeChange(current, size) {
        let data = this.state.searchData;
        data.page = current;
        data.size = size;
        this.handleSearchAdminList(data);
    };

    /**
     * 弹框显示/隐藏事件
     * @param visible
     */
    handleCancel(visible) {
        this.setState({isAddValid: visible})
    };

    /**
     * 删除管理员事件
     * @param id
     */
    handleDelete(id) {
        const _this = this;
        confirm({
            title: '',
            content: '确认要删除这条记录？',
            onOk() {
                app.post(requestUrl.DEL_ADMIN, {admin_id: id}).then((result) => {
                    if (result.code === 1) {
                        app.alert("删除成功", 'success', 3);
                        _this.handleAfterDel();
                    } else {
                        app.alert(result.msg, 'error', 3);
                    }
                })
            },
            onCancel() {
            },
        });
    };

    /**
     * 处理添加按钮事件
     */
    handleSubmit() {
        this.props.form.validateFields((error, values) => {
            if (!error) {
                let data = {
                    admin_username: values.username,
                    admin_password: values.password,
                    role_id: values.role_id,
                    admin_nickname: values.nickname
                };
                app.post(requestUrl.ADD_ADMIN, data).then((result) => {
                    if (result.code === 1) {
                        app.alert('添加成功', 'success', 3);
                        this.handleCancel(false);
                        this.handleRefresh();
                    } else {
                        app.alert(result.msg, 'error', 3);
                    }
                })
            }
        })
    };

    /**
     * 处理重置按钮事件
     */
    handleReset() {
        this.setState(({searchData: {}}));
        this.handleSearchAdminList();
    };
};

class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <Form className="login-form">
                        <Row>
                            <Col span={4}>
                                <FormItem label="账号" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('admin_username')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem label="昵称" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('admin_nickname')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label="角色" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('role_id')(
                                            <Select placeholder="请选择角色"
                                                    onChange={(value) => this.handleOnChange(value)}>
                                                {
                                                    this.props.roleItem.map((item) => {
                                                        return (
                                                            <Option key={item.role_id}
                                                                    value={item.role_id}>{item.role_name}</Option>
                                                        )
                                                    })
                                                }
                                            </Select>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col offset={2} span={4}>
                                <Button type="primary"
                                        onClick={() => this.handleSearchComplain()}
                                >
                                    查询
                                </Button>
                                <Button type="default"
                                        onClick={() => this.handleReset()}
                                        style={{marginLeft: '10px'}}
                                >
                                    重置
                                </Button>
                            </Col>
                        </Row>
                    </Form>
                </Row>
            </div>
        )
    };

    componentDidMount() {

    };

    /**
     * 获取搜索条件
     */
    handleSearchComplain() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 重置按钮事件
     */
    handleReset() {
        this.props.form.resetFields();
        this.props.handleReset();
    };

    /**
     * 处理输入框按下回车键的事件
     */
    handleOnPressEnter() {
        //调用获取搜索条件的函数
        this.handleSearchComplain();
    };

    /**
     * 处理下拉框选择变化事件
     * @param value
     */
    handleOnChange(value) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.role_id = value;
                this.props.clickSearch(values);
            }
        })
    };
};

const SearchLists = Form.create()(SearchList);
const AdminManages = Form.create()(AdminManage);
export default prop => (
    <Consumer>
        {
            props => (
                <AdminManages {...prop} {...props} />
            )
        }
    </Consumer>
);